<template>
  <div class="positionBox">
    <div id="allmap"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "AppMap",
  data() {
    return {
      map: null,
      fencePolygon: null,
      placeSearch: null,
      autoOptions: {
        // 搜索结果绑定的输入框
        input: "searchId",
        // 输出结果展示的元素 可自定义
        // output: 'search',
        city: "全国",
      },
      polygonPoints: [
        [116.397428, 39.90923],
        [116.407428, 39.91923],
        [116.417428, 39.90923],
        [116.397428, 39.90923],
      ],
      markers: [],

      // 搜索内容
      text: null,
    };
  },
  methods: {
   search() {

    this.placeSearch.search(this.text);
   },
    loadMap() {
      AMapLoader.load({
        key: "307b71604f49cef2ad34700f072d1179",
        plugins: ["AMap.ToolBar", "AMap.Scale"],

      }).then(AMap => {
        this.map = new AMap.Map("allmap", {
          resizeEnable: true,
          zoom: 10,
          center:
            [116.397428, 39.90923], // 设置一个中心点
        });

        // 地图控件
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());

        // 绘制围栏
        this.drawFence();
      }).catch(e => {
        console.error(e, "高德地图加载失败");
      });
    },
    drawFence() {
      this.markers = this.polygonPoints.map(([lng, lat], index) => {
        const marker = new AMap.Marker({
          position: [lng, lat],
          map: this.map,
          draggable: true,
          cursor: 'move',
          zIndex: 1000,
        });

        AMap.event.addListener(marker, 'dragend', () => {
          const newLngLat = marker.getPosition();
          this.polygonPoints[index] = [newLngLat.lng, newLngLat.lat];

          // 更新多边形路径
          if (this.fencePolygon) {
            this.fencePolygon.setPath(this.polygonPoints);
          } else {
            // 首次创建多边形
            this.fencePolygon = new AMap.Polygon({
              map: this.map,
              path: this.polygonPoints,
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 6,
              fillColor: '#1791fc',
              fillOpacity: 0.35,
            });

            // 添加点击事件
            this.fencePolygon.on('click', () => {
              alert('围栏被点击');
            });
          }
        });

        return marker;
      });
    }


    //
    //     // 监听拖动结束事件

    //     return marker;
    //   });
    //   // 可选：添加点击事件

    // },
  },
  mounted() {

    this.loadMap();

  },
};
</script>

<style scoped>
#allmap {
  width: 100%;
  height: 500px;
}
</style>
